/**
 * 绘制
 */
var map,plot,utils;
var changeFeature = {};
var beforeFeature;
var ESM = {};

//行政图和卫星图的图片数据加载list
var xzImageResourceList=[];
var wxImageResourceList=[];
var resourceType=1;
//百度地图层
var baiduMapLayer,baiduWeiXinMapLayer,cva_wLayer;
var pageNum=1;
var pageSize=10;
$(document).ready(function(){//访问后台地址，不修改
	utils = new ESM.Utils();
	// 判断加载地图的类型
    if (loadMapType=="b"){
    	//行政图
        baiduMapLayer = new ol.layer.Tile({
       	    source: new ol.source.BaiduMap()
       });
        //卫星图
        baiduWeiXinMapLayer = new ol.layer.Tile({
    	    source: new ol.source.BaiduMap({"mapType":"sat"}),
            projection: 'EPSG:3857'
        })
    }else{
    	//行政图
        baiduMapLayer = new ol.layer.Tile({
       	    source: new ol.source.TianMap()
        });
        
        if(mapModel == 1){
       	// 天地图的lable
            cva_wLayer = new ol.layer.Tile({
           	    source: new ol.source.TianMap({"mapType":"label"})
            });
        }
        //卫星图
        baiduWeiXinMapLayer = new ol.layer.Tile({
    	    source: new ol.source.TianMap({"mapType":"sat"}),
            projection: 'EPSG:3857'
        })
    }
	// 比例线
    var scaleLineControl = new ol.control.ScaleLine({className:'ol-scale-line'});
	map = new ol.Map({
    	 interactions: ol.interaction.defaults().extend([new ESM.Drag()]),
    	 controls: ol.control.defaults({
            attributionOptions: {
              collapsible: false
            },
            zoom: false
          }).extend([
            scaleLineControl
         ]),
         layers: loadMapType=="b" ? [baiduMapLayer,baiduWeiXinMapLayer] 
     			: mapModel == 1 ? [baiduMapLayer,cva_wLayer,baiduWeiXinMapLayer]:[baiduMapLayer,baiduWeiXinMapLayer],
         view: new ol.View({
             // 设置成都为地图中心center: ol.proj.transform([125.106361,46.593634], 'EPSG:4326', 'EPSG:3857'),
        	 // 125.106361,46.593634 	成都
        	 // 84.77,45.59				克拉玛依
             center: ol.proj.transform([84.77,45.59], 'EPSG:4326', 'EPSG:3857'),
             zoom: 8,
             minZoom: 3,
             maxZoom: 19,
         }),
         target: 'map'
     });
	
    //initPopup(map);
 	if(ESM.InfoWindow != undefined){
        global.infowindow = new ESM.InfoWindow({
            map:global.map,
            maxWidth:420,
            zIndex:1000
        });
	}
	
     //测距 面积
    if(ol.control.MeasureTool != undefined){
    	var MeasureTool = new ol.control.MeasureTool({
            sphereradius : 6378137,//sphereradius
         });

         global.map.addControl(MeasureTool);
    }
    //地图点击事件
    map.on('singleclick', onClickHandler);
    map.on('moveend', onMoveEndHandler);
    
    baiduMapLayer.setVisible(true); //显示行政
    baiduWeiXinMapLayer.setVisible(false); //关闭卫星
    
    
	plot = new olPlot(map, {
        zoomToExtent: true,
        isClear: true
    })
	
	plot.plotDraw.on('drawEnd', onDrawEnd)
	
	/*点击重点单位的选项，展示选项*/
	$("#teamSearEvent").click(function () {
		pageNum=1; 
		getTeams();
    });
	 //初始化聚合数据
    getClusterDataList();
	getTeams();
	moveCenter();
	//setTimeout(function(){getAllMapImages()}, 2000);
});

/**
* 显示矢量地图
**/
function showDiTu(){
	resourceType=1;
	for(j = 0,len=wxImageResourceList.length; j < len; j++) {
		var oid=wxImageResourceList[j].oid;
		removeImagesByid(oid);
	}
//	var layer = getLayerById('sys_baselayer');
//	if(layer) global.map.removeLayer(layer);
//	baiduMapLayer = new ol.layer.Tile({
//		source: new ol.source.BaiduMap()
//     });
//     baiduMapLayer.set('name', 'sys_baselayer');
//     baiduMapLayer.set('id', 'sys_baselayer');
//     baiduMapLayer.setZIndex(0);
//     global.map.addLayer(baiduMapLayer);
	 baiduMapLayer.setVisible(true); //显示行政
     baiduWeiXinMapLayer.setVisible(false); //关闭卫星
    // getAllMapImages();
}

/**
* 显示天地图卫星
**/
function showWeiXingTu(){
	resourceType=2;
	$('#scenebuildingList').find('li').each(function() {
        removeImagesByid($(this).attr("id"));
    });
	for(j = 0,len=xzImageResourceList.length; j < len; j++) {
		var oid=xzImageResourceList[j].oid;
		removeImagesByid(oid);
	}
//	baiduWeiXinMapLayer
//	var layer = getLayerById('sys_baselayer');
//	if(layer) global.map.removeLayer(layer);
//	    baiduMapLayer = new ol.layer.Tile({
//	    source: new ol.source.BaiduMap({"mapType":"sat"}),
//        projection: 'EPSG:3857'
//    })
//     baiduMapLayer.set('name', 'sys_baselayer');
//     baiduMapLayer.set('id', 'sys_baselayer');
//     baiduMapLayer.setZIndex(0);
//     global.map.addLayer(baiduMapLayer);
	 baiduMapLayer.setVisible(false); //显示卫星
     baiduWeiXinMapLayer.setVisible(true); //关闭行政
     //getAllMapImages();
}

function getAllMapImages(){
	var params = {"tenantId":tenantId,"type":resourceType};
    $.ajax({
		type : "get",
		url : "/mapimages?t="+new Date().getTime(),
		data: params,
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {
			if(data.data&&data.data.length>0){
				var addtomap=[];
				if(resourceType==1){
					xzImageResourceList=data.data;
				}else if(resourceType==2){
					wxImageResourceList=data.data;
				}
				for(j = 0,len=data.data.length; j < len; j++) {
					var d = data.data[j];
					if(d.imagePos && d.imagePos!=""){
						addtomap.push({url:d.imagePath,extent:d.imagePos,id:d.oid,imageId:d.oid,rotation:d.rotation});
					}
				}
				addImagesToMap(addtomap);
			}
		},error: function(request) {
			layer.msg("获取地图图片数据失败", {time: 2000});
        }
	})
}

function getClusterDataList(){
	var params = {"tenantId":tenantId}
	$.ajax({
		type : "get",
		url : "/teams/cluster?t="+new Date().getTime(),
		data: params,
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {	
			if(data.data){
				clusterDo(data.data);
			}
		},error: function(request) {
			layer.msg("获取聚合数据失败！", {time: 2000});
        }
	});
}


function getTeams(){
	$("#teamList").html("");
	var html ='';
	var keyWord=$("#teamKeyword").val();
	var params={"name":keyWord,"tenantId":tenantId,"pageNum":pageNum,"pageSize":pageSize};
    $.ajax({
		type : "get",
		url : "/teams?t="+new Date().getTime(),
		data: params,
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {	
			if(data.data&&data.data.length>0){
				var currentPage = Number(data.current);
				var totalPages = Number(data.pages);
				if(currentPage>=1 && totalPages>1){
					generatePagination(currentPage,totalPages,"teamPage");
				}
				for(j = 0,len=data.data.length; j < len; j++) {
					html+=getNameHtml(data.data[j],"teams");
				}
			}else{
				html+="<li class='NoTime'>暂无数据</li>";
			}
			$("#teamList").append(html);
			
			//注册删除事件
			$("#teamList").find('.unitDetails').click(function(){
				var id = $(this).attr("data");
				layer.confirm('是否删除该井队？', {
			        btn: ['确定','取消'] //按钮
			   },function(){
				   delTeam(id);
			   }, function(){
			   	layer.msg('已取消', {icon: 1, time: 1000});
			   });
			})
		},error: function(request) {
			layer.msg("获取井队数据失败！", {time: 2000});
        }
	});
}

function addTeam(){
	getAddHtml();
}

// 放大地图
function zoom(z){
    if(z == 1){
        map.getView().animate({zoom: map.getView().getZoom() + 1});
    }else{
        map.getView().animate({zoom: map.getView().getZoom() - 1});
    }
}
// 重新移动到地图初始位置。
function moveCenter () {
//    global.map.getView().animate({zoom: 8}, {center: ol.proj.transform([124.054602,41.847832], 'EPSG:4326', 'EPSG:3857')});
	global.map.getView().animate({zoom: 12}, {center: ol.proj.transform([teamList[0].lon,teamList[0].lat], 'EPSG:4326', 'EPSG:3857')});
}
//分页
function generatePagination(cp,tp,keyId){
	this.currentPage = Number(cp);
	this.totalPages = Number(tp);
	var jump_prev=currentPage>1?(currentPage-1):currentPage;
	var jump_next=(currentPage<totalPages)?(currentPage+1):totalPages;
	var pageList ="<a name='findPage' pageNum='"+jump_prev+"' class='front'><span></span></a>";
	var page_start = Number(currentPage)/5;
	if(page_start>1){
		pageList = getPageHtml(page_start*5-2,page_start*5+3,totalPages,pageList);
	}else{
		pageList = getPageHtml(1,6,totalPages,pageList);
	}
	pageList +="<a name='findPage' pageNum='"+jump_next+"' class='after'><span></span></a>";
	$("#"+keyId).html(pageList);
	$("#"+keyId).find("[name=findPage]").on("click",function(){
	   pageNum=$(this).attr("pageNum");  //获取链接里的页码  
	   getTeams();
	});  
}

function getPageHtml(start,end,totalPages,pageList){
	for(var i=start;i<=end;i++){
		if(i<=totalPages){
			var temp =""
			if(i==currentPage){
				temp="<a name='findPage' pageNum='"+i+"' class='onlink'>"+i+"</a>";
			}else{
				temp="<a name='findPage' pageNum='"+i+"'>"+i+"</a>";
			}
			pageList+=temp;
		}
	}
	return pageList;
}

/*显示详情弹框html*/
function getNameHtml(obj,type){
	obj.type='zddw';
	var html="<li>";
	    html+="<div class='listHd'><i class='address'></i>"+obj.name+"</div>"; 
//	    html+="<div style='width:13px; height:14px; display:inline-block; background: url('/images/detailsICON.png') no-repeat;  position: absolute; right: 5px; top:8px;'></div>";
	    html+="<div class='listFrom' onclick='getDetailHtml("+ JSON.stringify(obj)+",\""+type+"\")'>";
	    html+="<p><span class='color3'>联系人(电话):</span><span>"+obj.phone+"</span></p>";
		html+="<p><span class='color3'>备注:</span><span>"+obj.remark+"</span></p>";	
		html+="</div>";			
		/*html+="<div class='unitDetails' data="+obj.oid+"></div>";*/
		html+="</li>";
	return html;
}

/*显示详情弹框html*/
function getDetailHtml(obj,type){
	$("#teamBox").show().html("");
	$("#addTeamBox").hide().html("");
	var title="井队详情";
	var html='<div class="gisBoxHd">'+title+'</div>';
		html+='<div class="listFrom">';
		html+='<p><span class="color3">名称：</span><input readonly class="lonatInput" id="teamName" value='+obj.name+'></input></p>';
		html+='<p><span class="color3">联系人(电话)：</span><input readonly class="lonatInput" id="teamPhone" value='+obj.phone+'></input></p>';
		html+='<p><span class="color3">备注：</span><input readonly class="lonatInput" id="teamRemark" value='+obj.remark+'></input></p>';
		html+='<p><span class="color3" style="line-height: 28px;">经纬度：</span><input readonly class="lonatInput" id="lonLat" value='+obj.lon+","+obj.lat+' /></p>';
		html+='<p>';
		/*html+='<div class="gisBoxBtn"><span class="punctuation" onclick="getLoation(\''+obj.oid+'\',\''+obj.name+'\',\''+type+'\')"><i></i>标注</span>';
		html+='<span class="preview" onclick="saveLoation(\''+obj.oid+'\',\''+type+'\',false)">保存</span>';
		html+='<span class="cancel" onclick="hideGisBox(\''+type+'\')">取消</span>';
		html+='</div>';*/
		html+='</div>';
	$("#teamBox").append(html);
	gotoLocation(obj);
}

function generateUUID() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random()*16)%16 | 0;
    d = Math.floor(d/16);
    return (c=='x' ? r : (r&0x3|0x8)).toString(16);
  });
  return uuid;
};

function delTeam(id){
   $.ajax({
		type : "DELETE",
		url : "/teams/"+id,
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {
			if(data.data&&data.data==1){
				layer.msg('删除成功', {icon: 1, time: 1000});
				getTeams();
				getClusterDataList();
				$("#teamBox").hide().html("");
			}else{
				layer.msg('删除失败', {icon: 1, time: 1000});
			}
		},error: function(request) {
			layer.msg("删除失败", {time: 2000});
		}
	});
}



function getAddHtml(){
	var obj={};
	var type="teams";
	obj.type='zddw';
	obj.oid = generateUUID();
	$("#addTeamBox").show().html("");
	$("#teamBox").hide().html("");
	var title="添加井队";
	var html='<div class="gisBoxHd">'+title+'</div>';
		html+='<div class="listFrom">';
		html+='<p><span class="color3">名称：</span><input class="lonatInput" id="teamName"></input></p>';
		html+='<p><span class="color3">联系人(电话)：</span><input class="lonatInput" id="teamPhone"></input></p>';
		html+='<p><span class="color3">备注：</span><input class="lonatInput" id="teamRemark"></input></p>';
		html+='<p><span class="color3" style="line-height: 28px;">经纬度：</span><input class="lonatInput" id="lonLat" /></p>';
		html+='<p>';
		html+='<div class="gisBoxBtn"><span class="punctuation" onclick="addLoation(\''+obj.oid+'\',\''+type+'\')"><i></i>标注</span>';
		html+='<span class="preview" onclick="saveLoation(\''+obj.oid+'\',\''+type+'\',true)">保存</span>';
		html+='<span class="cancel" onclick="hideAddTeamBox(\''+type+'\')">取消</span>';
		html+='</div>';
		html+='</div>';
	$("#addTeamBox").append(html);
}
function hideAddTeamBox(type){
	$("#addTeamBox").hide().html("");
	var layerId = type+'MarkerClusterLayer';
	if(changeFeature.getId){
		var fid = changeFeature.getId();
    	removeFeatureById(layerId,fid);
	}
}

function addLoation(id,type){
	var teamName=$("#teamName").val();
	if(teamName==null || teamName ==''){
		layer.msg("请输入名称", {time: 1000});
		return;
	}
	var params ={};
	params.oid = id;
	params.name =teamName;
	params.clusterType=type;
	params.imagePath='/mapIcon/mapFixedIcon/zhongdian.png';
	params.isCluster=true;
	params.clusterImagePath='/mapIcon/mapFixedIcon/zhongdian.png';
	params.isSyn=false;
	params.isSave=false;
	params.recordType='getDataLocation';
	params.action="获取坐标点";
	addMakerEngine(params);
}

/**
 * 隐藏详情弹框
 * @returns
 */
function hideGisBox(type){
	$("#teamBox").hide().html("");
	var layerId = type+'MarkerClusterLayer';
	if(changeFeature.getId){
		var fid = changeFeature.getId();
    	removeFeatureById(layerId,fid);
	}
}


//保存
function saveLoation(id,type,isAdd){
	var name = $("#teamName").val();
	if(name==null||name==''){
		layer.msg("请输入名称");
		return;
	}
	var phone = $("#teamPhone").val();
	var remark=$("#teamRemark").val();
	var lonLat = $("#lonLat").val();
	if(lonLat==null||lonLat==''){
		layer.msg("请获取井队经纬度");
		return;
	}
	var params ={};
	params.oid = id;
	params.tenantId = tenantId;
	params.lonLat=lonLat;
	params.name=name;
	params.phone=phone;
	params.remark=remark;
	$.ajax({
		type : isAdd?"post":"put",
		url : "/teams",
		data: JSON.stringify(params),
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {	
			if(data.httpCode==200){
				if(data.data&&data.data==1){
					getTeams();
					getClusterDataList();
					var layerId = type+'MarkerClusterLayer';
					if(changeFeature.getId){
						var fid = changeFeature.getId();
				    	removeFeatureById(layerId,fid);
					}
			    	if(isAdd){
			    		$("#addTeamBox").hide().html("");
			    	}
				}
			}else{
				layer.msg(data.msg,{icon: 2,time: 2000});
			}
		},error: function(request) {
			layer.msg(isAdd?"添加井队失败！":"更新井队失败！",{icon: 2,time: 2000});
        }
	});   
}

function getLoation(id,name,type){
	var params ={};
	params.oid = id;
	params.name =name;
	params.clusterType=type;
	params.imagePath='/mapIcon/mapFixedIcon/zhongdian.png';
	params.isCluster=true;
	params.clusterImagePath='/mapIcon/mapFixedIcon/zhongdian.png';
	params.isSyn=false;
	params.isSave=false;
	params.recordType='getDataLocation';
	params.action="获取坐标点";
	addMakerEngine(params);
}

/*左侧点击道路定位并弹出详情*/
function gotoPointLocation(obj){
	var json = JSON.parse(obj.content);
	var format = new ol.format.GeoJSON();
	var feature = plot.plotUtils.toFeature(json);
	addFeature(feature);
}

function onMoveEndHandler(event){
	//console.log("moveend");
}

/**
 * 聚合接口
 * */
function clusterDo(data){
	var fmap = new HashMap();
	var format = new ol.format.GeoJSON();
	var features = format.readFeatures(data);
	features.forEach(function(feature){
		feature.set('cluster',true)
		var prop = feature.getProperties();
		var catecd = prop.catecd;
		if(fmap.containsKey(catecd)){
			fmap.get(catecd).push(feature);
		}else{
			var fs = [];
			fs.push(feature);
			fmap.put(catecd,fs);
		}
	});
	var keys =  fmap.keys();
	for(var i=0;i<keys.length;i++){
		var layerId = keys[i]+"ClusterLayer";
		var layer = layerIsExist(layerId,map);
		if(!layer){
			layer = createClusterLayer(layerId,keys[i]);
			map.addLayer(layer);
		}
		addFeatureToLayer(fmap.get(keys[i]),layer,true)
	}
}

/**
 * 图标点击事件
 * */
function onClickHandler(event){
	var coord = event.coordinate;//地图点击位置的经纬度数值
	feature = map.forEachFeatureAtPixel(event.pixel, function (feature) {
		if(feature.get('features')){
			if(feature.get('features').length>1){
				var coordinate_ = feature.getGeometry().getCoordinates();
				map.getView().animate({zoom: map.getView().getZoom() + 1},{center: coordinate_},{duration:1000});
				return null;
			}else{
				return feature.get("features")[0];
			}
		}else{
			return feature
		}
	})
	if (feature && feature.get('isPlot') && !plot.plotDraw.isDrawing()) {
		plot.plotEdit.activate(feature);
		changeStyle(feature);
	} else {
		plot.plotEdit.deactivate();
	}
	 /**
	 * mark点击功能
	 */
	if(feature&&feature.get('cluster')){
		return;
	}
}

/**
 * 第4个功能点
 * */
function changeStyle(feature){
	changeFeature = feature;
}

//图层面板扎图标
function makerFireEngine(dtPath,id,iconType,name,jhPath,clusterType){
	var params ={};
	params.clusterType='accident';
	params.imagePath="/mapIcon/mapPanel/mee-12.png";
	params.isCluster=true;
	params.clusterImagePath="/mapIcon/mapPanel/mee-12.png";
	params.isSyn=false;
	params.isSave=false;
	params.recordType='road';
	params.action="编辑道路";
	params.name=name;
	addRoadLineEvent("dlhz",params);
}

/**
* 调用marker标绘
* */
function addMakerEngine(params){
	params.type = 'marker';
    activate('Point',params);
}

/**
 * 绘制功能结束的回调
 * */
function onDrawEnd(event){
	var feature = event.feature;
    var params = feature.get("params");
    var fid = params.oid;
    feature.setId(createRandomId());
	feature.set("name",params.name);
	feature.set("scolor","#ff00ff");
	var iconType = params.recordType;
	if(iconType=="getDataLocation"){
    	var layerId = params.clusterType+'MarkerClusterLayer';
    	if(changeFeature.getId){
    		var fid = changeFeature.getId();
        	removeFeatureById(layerId,fid);
    	}
    	var clayer = layerIsExist(layerId,map);
 		if(!clayer){
 			clayer = createMakerClusterLayer(layerId,params.clusterType);
 			map.addLayer(clayer);
 		}
 		featureIsExist(feature,clayer,true);
 		feature.set('plotType','Marker');
 		
 		var lonlat3857 = feature.getGeometry().getCoordinates();
 		var lon = ol.proj.transform(lonlat3857, 'EPSG:3857', 'EPSG:4326')[0].toFixed(6);
		var lat = ol.proj.transform(lonlat3857, 'EPSG:3857', 'EPSG:4326')[1].toFixed(6);
		var cLonLat = lon + ',' + lat;
		$("#lonLat").val(cLonLat);
    }
	changeFeature = feature;
	feature.scolor = "#000";
	plot.plotEdit.activate(feature);
}

/*左侧点击定位*/
function gotoLocation(obj){
	leftRecordLocation(Number(obj.lon),Number(obj.lat),obj.type,obj.name,obj.oid,obj.other);
	//leftRecordLocation(Number(obj.lon),Number(obj.lat),obj.type,obj.name,obj.id,"",obj.other);
}
/**
 * 点击左侧结果列表定位
 * @param type 类型
 * @param id 主键
 * */
function leftRecordLocation(lon,lat,type,name,id,other){
	var layerId = type+'ClusterLayer';
	var layer = layerIsExist(layerId,map);
	var coords = [];
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(id);
		coords = feature.getGeometry().getCoordinates();
		centerAndZoom(coords,17);
	}
	return coords;
}


/**
 * 初始化弹出窗口
 * */
function initPopup(map){
	var element = document.createElement('div');
	element.className='ol-popup';
	element.id='popup';
	var child =  '<a href="#" id="popup-closer" class="ol-popup-closer"></a>';
	child += '<div id="popup-content"></div>';
	element.innerHTML += child;
	var overlay = new ol.Overlay({
		id: 'overlay',
		element: element,
		offset:[0,5],
		autoPan: true,
		positioning:'top-center',
		autoPanAnimation: {
			duration: 250
        }
	});
	map.addOverlay(overlay);
	$("#popup-closer").click(function(event){
		close();
	})
}


/**
 * 关闭弹出窗口
 * */
function close(){
	var overlay = map.getOverlayById('overlay');
	overlay.setPosition(undefined);
    $("#popup-closer").blur();
    $("#popup-content").html('');
    return false;
}

/**
 * 设置弹出内容
 * */
function setContent(html){
	$("#popup-content").html(html);
}

/**
 * 在坐标点位置打开窗口
 * */
function setPopupPosition(coord){
	var overlay = map.getOverlayById('overlay');
	overlay.setPosition(coord);
}

/**
 * 标注回显功能
 * */
function addFeatureToMap(feature,id){
	feature.setId(id);
	var params = feature.get("params");
	feature.set("name",params.name);
	feature.set("desc",params.desc);
	addFeature(feature);
}


/**
 * 楼块标绘
 * */
function addPolygonEngine(params){
	activate('Polygon',params);
}

function buffer(geometry){
	var parser = new jsts.io.OL3Parser();
	var jstsGeom = parser.read(geometry);
	var buffered = jstsGeom.buffer(40);
	var bufferGeom = parser.write(buffered);
	var feature = new ol.Feature({
		geometry:bufferGeom
	});
	return feature;
}
/**
 * 激活绘制功能
 * */
function activate(type,params){
	plot.plotEdit.deactivate();
    plot.plotDraw.active(type, params);
}

//救援路线
function makerEscapeLineEngine(oid,iconType,name){
	var params ={};
	params.oid=oid;
	params.name=name;
	params.isSyn=true;
	params.isSave=true;
	params.recordType="4";
	params.action="救援路线";
	params.scolor="red";
	addSpecialLineEvent('jylx',params);
}

/**
* 应急路线
* @param type 应急路线类型
* @param color 路线颜色
* */
function addSpecialLineEvent(type,params){
	params.type=type;
	params.isSpecial=true;
	activate("Polyline",params);
}

/**
 * 绘制道路
 * */
function addRoadLineEvent(type,params){
	params.type = type;
	params.isSpecial = false;
	activate("Polyline",params);
}

/**
 * 添加罐体
 * */
function addOilcanFeature(feature){
	var layer = layerIsExist('oilcanMakerLayer',map);
	if(!layer){
		layer = createNoStyleLayer('oilcanMakerLayer');
		map.addLayer(layer);
	}
	var params = feature.get(params);
	var image = params.image;
	var id = params.id;
	var style = new ol.style.Style({
		image : new ol.style.Icon({
			src : baseFileUrl+image,
			anchor : [ 0.5, 0.5 ]
		}),
		text : new ol.style.Text({
			text : params.name,
			offsetY : 10,
			font : 'bold 12px sans-serif',
			fill : new ol.style.Fill({
				color : '#84C1FF'
			}),
			stroke : new ol.style.Stroke({
				color : '#ECF5FF',
				width : 3
			})
		})
	});
	feature.setStyle(style);
	feature.setId(id);
	layer.getSource().addFeature(feature);
	//添加罐体外围图形
	var coord = feature.getGeometry().getCoordinates();
	addOilcanOuterFeature(coord,params.distance);
}

/**
 * 更新罐体数据
 * */
function updateOilcanFeature(id,distance){
	var layer = layerIsExist('oilcanMakerLayer',map);
	if(layer){
		var feature = layer.getSource().getFeatureById(id);
		if(feature){
			var params = feature.get('params');
			params.distance = distance;
			updateOilcanOuterFeature(id,distance,center);
		}
	}
}

/**
 * 删除罐体图标
 * */
function removeOilcanFeature(id){
	var layer = layerIsExist('oilcanMakerLayer',map);
	if(layer){
		var feature = layer.getSource().getFeatureById(id);
		if(feature){
			layer.getSource().removeFeature(feature);
			removeOilcanOuterFeature(id);
			var center = feature.getGeometry().getCoordinates();
			
		}
	}
}

/**
 * 添加罐体的外围图形
 * */
function addOilcanOuterFeature(center,distance){
	var layer = layerIsExist('markerOuterLayer',map);
	if(!layer){
		layer = createNoStyleLayer('markerOuterLayer');
		map.addLayer(layer);
	}
	var id = params.id;
	var distance = params.distance;
	var point = utils.fromLonLat(utils.calculatePoint(utils.toLonLat(center),distance,1.57));
	var radius = utils.calculateRadius(center,point);
	var circle = new ol.geom.Circle(center,radius);
	var feature = new ol.Feature({
		geometry: circle
	});
	var style = new ol.style.Style({
		fill:null,
		stroke: new ol.style.Stroke({
			color:'#ff00ff',
			width: 1
		})
	});
	feature.setStyle(style);
	feature.setId(id);
	layer.getSource().addFeature(feature);
}
/**
 * 根据id删除罐体外围图形
 * */
function removeOilcanOuterFeature(id){
	var layer = layerIsExist('markerOuterLayer',map);
	if(layer){
		var feature = layer.getSource().getFeatureById(id);
		if(feature){
			layer.getSource.removeFeature(feature);
		}
	}
}
/**
 * 更新
 * */
function updateOilcanOuterFeature(id,distance,center){
	var point = utils.fromLonLat(utils.calculatePoint(utils.toLonLat(center),distance,1.57));
	var radius = utils.calculateRadius(center,point);
	var circle = new ol.geom.Circle(center,radius);
	var layer = layerIsExist('markerOuterLayer',map);
	if(layer){
		var feature = layer.getSource().getFeatureById(id);
		if(feature){
			feature.setGeometry(circle);
		}
	}
}

/**
 * 添加标绘要素
 * */
function addFeature(feature){
	var layer = layerIsExist('geographicEditLayer',map);
	if(!layer){
		layer = createMarkLayer('geographicEditLayer');
		map.addLayer(layer);
	}
	layer.getSource().addFeature(feature);
}

/**
 * 
 * 根据ID删除要素
 * */
function removeFeatureById(layerType,id){
	var layer = layerIsExist(layerType,map);
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(id);
		if(feature){
			layer.getSource().getSource().removeFeature(feature);
			//close();
		}
		
	}
}
/**
 * 清空图层
 * */
function clearLayer(){
	clearLayerByIds(['plotLayer']);
}

function remove(){
	var feature = plot.plotEdit.getFeature();
	var layer = layerIsExist('plotLayer',map);
	if(layer){
		layer.getSource().removeFeature(feature);
	}
	plot.plotEdit.deactivate();
}

/**
 * 显示场景搭建历史
 * */
/*function addImagesToMap(images){
	var group = layerIsExist('imagesGroup',map);
	if(!group){
		group = createGroupLayer('imagesGroup');
		map.addLayer(group);
	}
	for(var i=0;i<images.length;i++){
		var image = images[i];
		var layer = new ol.layer.Image({
			source: new ol.source.ImageStatic({
				url:baseFileUrl+image.url,
				crossOrigin: '',
				projection: 'EPSG:3857',
	            imageExtent: image.extent.split(",")
			})
		});
		if(image.id){
			layer.set('id',image.id);
			removeImagesByid(image.id);
		}
		group.getLayers().push(layer);
	}
}*/


/**
 * 显示场景搭建历史
 * */
function addImagesToMap(images){
	var group = layerIsExist('imagesGroup',map);
	if(!group){
		group = createGroupLayer('imagesGroup');
		map.addLayer(group);
	}
	for(var i=0;i<images.length;i++){
		var image = images[i];
//		var layer = new ol.layer.Image({
//			source: new ol.source.ImageStatic({
//				// 全路径才能给同房间推送过去。
//				url:image.url,
//				crossOrigin: '',
//				projection: 'EPSG:3857',
//	            imageExtent: image.extent.split(",")
//			})
//		});
//		if(image.id){
////			console.log(image.id);
//			layer.set('id',image.id);
//			removeImagesByid(image.id);
//		}
//		layer.setZIndex(2);
//		group.getLayers().push(layer);
		
		
		var sourceFeatures = new ol.source.Vector();
		var layer = new ol.layer.Vector({source: sourceFeatures});
		var extent = image.extent.split(",");
		var feature = new ol.Feature({
		    geometry: new ol.geom.Point([extent[0]-(extent[0]-extent[2])/2,extent[1]-(extent[1]-extent[3])/2])
		});
		feature.set('id',image.id);
		var resolution = map.getView().getResolution();
		var canvas = createViewCanvasForm(feature,image.url,(extent[2]-extent[0])/resolution,(extent[3]-extent[1])/resolution);
		feature.set('canvas',canvas);
		feature.set('rotation',image.rotation);
		var style = function(feature, resolution) {
			var initZoom = resolution;
			var canvas = feature.get('canvas');
			if(feature.get('scale')){
				initZoom=feature.get('scale');
			}else{
				feature.set('scale',resolution);
			}
	    	return new ol.style.Style({
			    image: new ol.style.Icon({
			    	img: canvas,
                    imgSize: [canvas.width, canvas.height],
			        anchor: [0.5, 0.5],
			        anchorXUnits: 'fraction',
			        anchorYUnits: 'fraction',
			        opacity: 1,
			        rotation:feature.get('rotation'),
			        scale:initZoom/resolution
			    })
			});
		}
		feature.setStyle(style);
		sourceFeatures.addFeature(feature);
		
		if(image.id){
			layer.set('id',image.id);
			removeImagesByid(image.id);
		}
			
		layer.setZIndex(2);
		group.getLayers().push(layer);
	}
}

function createViewCanvasForm(feature,url,width,height) {
	var span = 5;
	var canvas = document.createElement('canvas');
    canvas.width = width+span*2;
    canvas.height = height+span*2;
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.src = url;
    img.onload = function(){
    	ctx.drawImage(img, 0,0, img.width, img.height,span,span,width,height);
    };
    return canvas;
}

/**
 * 删除场景搭建历史
 * */
function removeImagesByid(id){
	var layer;
	var group = layerIsExist('imagesGroup',map);
	group.getLayers().forEach(function(lay){
		if(lay.get('id')==id){
			layer = lay;
		}
	});
	if(layer){
		group.getLayers().remove(layer);
	}
}

function clearImagesGroup(){
	var group = layerIsExist('imagesGroup',map);
	if(group){
		map.removeLayer(group);
	}
}

/**
* 保存操作记录的公共方法
* @param params t_incident_record 对象 操作人director 类型type 房间号roomId 子动作action 动作描述actionDesc 动作内容content
* @param callback 回调参数
* */
function saveRecord(params,callback){
	doCallback = function (fn, args) {
		return fn.apply(this, args);
	}
	if(!params.type){
		params.type=params.recordType;
	}
	var url = baseUrl+'/webApi/insertIncidentRecord.jhtml';
	$.ajax({
		type:'POST',
		url: url,
		headers: {"Content-Type": "application/json;charset=utf-8"},
		data: JSON.stringify(params),
		dataType:'JSON',
		success: function(data){
			if(data){
				if(callback){
				  doCallback(callback,[data]);
				}
			}
		}
	});
}
function updateRecord(params,callback){
	doCallback = function (fn, args) {
		return fn.apply(this, args);
	}
	params.type=params.recordType;
	var url = baseUrl+'/webApi/updateIncidentRecord.jhtml';
	$.ajax({
		type:'POST',
		url: url,
		headers: {"Content-Type": "application/json;charset=utf-8"},
		data: JSON.stringify(params),
		dataType:'JSON',
		success: function(data){
			if(data){
				if(callback){
					doCallback(callback,[data]);
				}
			}
		}
	});
}

/**
 * svg转png
 * */
function getVectorImage(src, width, height) {
	var canvas = document.createElement('canvas');
	canvas.setAttribute("width", width);
	canvas.setAttribute("height", height);
	var ctx = canvas.getContext("2d");
	var img = new Image();
	img.onload = function() {
		ctx.drawImage(img, 0, 0, width, height);
	}
	img.src = src;
	return canvas;
}

// 重新移动到地图初始位置。
function moveCenter () {
//    global.map.getView().animate({zoom: 8}, {center: ol.proj.transform([124.054602,41.847832], 'EPSG:4326', 'EPSG:3857')});
	map.getView().animate({zoom: 12}, {center: ol.proj.transform([teamList[0].lon,teamList[0].lat], 'EPSG:4326', 'EPSG:3857')});
}

/**
 * 定位功能
 * */
function centerAt(id){
	var layer = layerIsExist('geographicEditLayer',map);
	if(layer){
		if(beforeFeature){
			var bf = layer.getSource().getFeatureById(beforeFeature.id);
			bf.set('scolor',beforeFeature.scolor);
		}
		var feature = layer.getSource().getFeatureById(id);
		if(feature){
			var point;
			var geometry = feature.getGeometry();
			var type = geometry.getType();
			if(type=="Point"){
				point = geometry.getFirstCoordinate();
			}else if(type=="LineString"){
				beforeFeature = null;
				beforeFeature = {};
				beforeFeature.id = feature.getId();
				beforeFeature.scolor = feature.get('scolor');
				feature.set('scolor','#00ff00');
				point = geometry.getFirstCoordinate();
			}else if(type=="Polygon"){
				point = geometry.getInteriorPoint();
			}
			centerAndZoom(point,map.getView().getZoom());
		}
	}
}

/**
 * 定位
 * */
function centerAndZoom(point,zoom){
	if(zoom){
		map.getView().animate({center: point}, {zoom: zoom});
	}else{
		map.getView().animate({center: point});
	}
}

//生成随机数
function createRandomId() {
    return (Math.random()*10000000).toString(16).substr(0,4)+'-'+(new Date()).getTime()+'-'+Math.random().toString().substr(2,5);
}





